package org.jeecg.zhenxuan.CommonUtils;

//import net.sf.json.JSONObject;
//import org.apache.commons.codec.digest.DigestUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 根据支付通知字串生成待签字符串
 * @author lishuzhen
 */
public class SignatureUtil {


    /**
     * 根据支付通知字串生成待签字符串
     * @param
     * @return
     */
    public static String makeSignature(JSONObject json, String md5Key){

        Map<String, String> params = jsonToMap(json);

        String preStr = buildSignString(params); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串

        String text = preStr + md5Key;

        String signature = DigestUtils.md5DigestAsHex(getContentBytes(text)).toUpperCase();
//        String signature = DigestUtils.md5Hex(getContentBytes(text)).toUpperCase();

        return signature;
    }

    /**
     * 排序
     * @param params
     * @return
     */
    public static Map<String, String> rankMap(Map<String, String> params){
        //非空判断
        if (params == null || params.size() == 0) {
            return null;
        }
        //获得map的key集合
        List<String> keys = new ArrayList<>(params.size());

        //遍历
        for (String key : params.keySet()) {
            if ("sign".equals(key))
                continue;
            if (StringUtils.isEmpty(params.get(key)))
                continue;
            keys.add(key);
        }
        //排序
        Collections.sort(keys);

        Map<String, String> map =new HashMap<>();

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            map.put(key,value);
        }


        return map;
    }

    /**
     * 根据map构建签名字符串
     * @param params
     * @return
     */
    public static String buildSignString(Map<String, String> params) {
        //非空判断
        if (params == null || params.size() == 0) {
            return "";
        }
        //获得map的key集合
        List<String> keys = new ArrayList<>(params.size());

        //遍历
        for (String key : params.keySet()) {
            if ("sign".equals(key))
                continue;
            if (StringUtils.isEmpty(params.get(key)))
                continue;
            keys.add(key);
        }
        //排序
        Collections.sort(keys);

        //拼接字符串
        StringBuilder buf = new StringBuilder();

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            System.out.println(value);
            if (i == keys.size() - 1) {
                // 拼接时，不包括最后一个&字符
                buf.append(key + "=" + value);
            } else {
                buf.append(key + "=" + value + "&");
            }
        }

        return buf.toString();
    }

    /**
     * 根据编码类型获得签名内容byte[]
     * @param content
     * @return
     */
    public static byte[] getContentBytes(String content) {
        try {
            return content.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("签名过程中出现错误");
        }
    }

    /**
     * 使json-lib来进行json到map的转换，fastjson有排序问题，不能用
     * @param json
     * @return
     */
    public static Map<String, String> jsonToMap(JSONObject json) {
        Map<String, String> map = new HashMap<>();
        for (Object key : json.keySet()) {
//            String value = json.optString((String) key);
            String value = json.getString((String) key);
            map.put((String) key, value);
        }
        return map;
    }
}
